package com.ghsc.ghxc.jsb.ui.integral.activity

import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.view.KeyEvent
import android.view.inputmethod.EditorInfo
import android.widget.EditText
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.cn.appcore.base.BaseVMActivity
import com.cn.appcore.ext.encodeToStr
import com.cn.appcore.ext.loge
import com.cn.appcore.ext.setSingleClickListener
import com.cn.appcore.ext.showToast
import com.cn.appcore.utils.GsonUtil
import com.cn.appcore.utils.KeyboardUtils
import com.cn.appcore.widget.RefreshHelper
import com.flyco.roundview.RoundLinearLayout
import com.ghsc.ghxc.jsb.R
import com.ghsc.ghxc.jsb.config.CustKey
import com.ghsc.ghxc.jsb.config.LoginHelper
import com.ghsc.ghxc.jsb.databinding.ActivitySpecUpBinding
import com.ghsc.ghxc.jsb.ext.intentExtras
import com.ghsc.ghxc.jsb.ui.integral.IntegralSupermarketViewModel
import com.ghsc.ghxc.jsb.ui.integral.bean.CustSkuItemBean
import com.ghsc.ghxc.jsb.utils.StringUtil
import com.google.gson.Gson
import java.net.URLEncoder
import java.nio.charset.StandardCharsets


/**
 * 项目：GuoHuaJsb
 * 包名：com.ghsc.ghxc.jsb.ui.integral.activity
 * 类名：SpecUpActivity
 * 创建时间：2024/5/23 11:11
 * 创建人 @author： xiaolin
 * 描述 ：Todo...修改规格
 */
class SpecUpActivity : BaseVMActivity<IntegralSupermarketViewModel, ActivitySpecUpBinding>()  {
    override fun attachLayoutRes(): Int {
        return R.layout.activity_spec_up
    }

    override fun attachVMClass(): Class<IntegralSupermarketViewModel>? {
        return IntegralSupermarketViewModel::class.java
    }
    private val pid: String by intentExtras("pid","")




    private val mAdapter by lazy { ListAdapter() }
    var mList = arrayListOf<CustSkuItemBean>()
    override fun initImmersionBar() {
        super.initImmersionBar()
        mImmersionBar!!.statusBarDarkFont(true).init()
    }
    override fun initView() {
        KeyboardUtils.fixAndroidBug5497(this)
        binding.bar.topTitle.text="编辑规格"
        binding.bar.topLeftView.setSingleClickListener {
            hideKeyboard(binding.etName)
            finish()
        }


        binding.rvList.layoutManager = LinearLayoutManager(this)
        binding.rvList.adapter = mAdapter
        mAdapter.replaceData(mList)
        mAdapter.setEmptyView(R.layout.layout_order_empty)



        //获取规格
        getSkuData(pid)

    }
    //获取规格
    fun getSkuData(pid:String){
        //商品规格
        val map: HashMap<String, Any> = HashMap()
        map["pid"] = pid
        GsonUtil.mapToJsonStrObjEncryption(map)?.let { it1 -> mViewModel.onSkuDetailMethod(it1) }
    }
    override fun initClickListener() {
        super.initClickListener()
        binding.llBtnClose.setSingleClickListener {
            binding.etName.setText("")
        }
        binding.etName.setOnEditorActionListener(object : TextView.OnEditorActionListener {
            override fun onEditorAction(
                v: TextView,
                actionId: Int,
                event: KeyEvent?
            ): Boolean {
                if (actionId == EditorInfo.IME_ACTION_DONE) {
                    // 先隐藏键盘
                    KeyboardUtils.hideKeyboard(v)
                    // 搜索，进行自己要的操作...
                    if (binding.etName.text.toString().trim().isNotEmpty()){
                        if (mAdapter.data.size>0){
                            var isAdd=true
                            for (bean in mAdapter.data){
                                if (TextUtils.isEmpty(bean.skuname) || TextUtils.isEmpty(bean.price) || TextUtils.isEmpty(bean.skuprice) || TextUtils.isEmpty(bean.stock)){
                                    if(!TextUtils.isEmpty(bean.skuname))
                                        showToast("请先完善${bean.skuname}规格的填写")
                                    else showToast("请先完善规格的填写")
                                    isAdd=false
                                    break
                                }
                            }
                            if(isAdd){
                                mList.add(CustSkuItemBean(images="",skuname=binding.etName.text.toString().trim(),price="",skuprice="",stock=""))
                                mAdapter.replaceData(mList)
                                binding.etName.setText("")
                            }
                        }else{
                            mList.add(CustSkuItemBean(images="",skuname=binding.etName.text.toString().trim(),price="",skuprice="",stock=""))
                            mAdapter.replaceData(mList)
                            binding.etName.setText("")
                        }

                    }else{
                       showToast("请输入规格名称")
                    }
                    return true
                }
                return false
            }
        })
        binding.btnAdd.setSingleClickListener {
            //添加
            if (binding.etName.text.toString().trim().isNotEmpty()){
                if (mAdapter.data.size>0){
                    var isAdd=true
                    for (bean in mAdapter.data){
                        if (TextUtils.isEmpty(bean.skuname) || TextUtils.isEmpty(bean.price) || TextUtils.isEmpty(bean.skuprice) || TextUtils.isEmpty(bean.stock)){
                            if(!TextUtils.isEmpty(bean.skuname))
                                showToast("请先完善${bean.skuname}规格的填写")
                            else showToast("请先完善规格的填写")
                            isAdd=false
                            break
                        }
                        mAdapter.notifyDataSetChanged()
                    }
                    if(isAdd){
                        mList.add(CustSkuItemBean(images="",skuname=binding.etName.text.toString().trim(),price="",skuprice="",stock=""))
                        mAdapter.replaceData(mList)
                        binding.etName.setText("")
                    }
                }else{
                    mList.add(CustSkuItemBean(images="",skuname=binding.etName.text.toString().trim(),price="",skuprice="",stock=""))
                    mAdapter.replaceData(mList)
                    binding.etName.setText("")
                }

            }else{
                showToast("请输入规格名称")
            }

        }

        binding.btnPut.setSingleClickListener {
            if (mAdapter.data.size>0){
                mAdapter.notifyDataSetChanged()
                var isAdd=true
                for (bean in mAdapter.data){
                    if (TextUtils.isEmpty(bean.skuname) || TextUtils.isEmpty(bean.price) || TextUtils.isEmpty(bean.skuprice) || TextUtils.isEmpty(bean.stock)){
                        showToast("请先完善规格的填写")
                        isAdd=false
                        break
                    }
                }
                if(isAdd){
                    for(i in mAdapter.data.indices)
                        mAdapter.data[i].skuid=i
                    var json=Gson().toJson(mAdapter.data)
                    val encodedUrl = URLEncoder.encode(json, StandardCharsets.UTF_8.toString())
                        .replace("\\+".toRegex(), "%20")
                    val base64String =encodedUrl.encodeToStr()
                    val map: HashMap<String, Any> = HashMap()
                    map["pid"] = pid
                    map["skuinfo"] = base64String
                    loge("请求接口="+map.toString())
                    GsonUtil.mapToJsonStrObjEncryption(map)?.let { it1 -> mViewModel.onUpdSkuMethod(it1) }
                }
            }else showToast("请先添加规格")
        }


    }


    override fun initRequestObserver() {
        super.initRequestObserver()
        mViewModel.apply {
            errorMsg.observe(this@SpecUpActivity) {
                showToast(it)
            }
            againLoginMsg.observe(this@SpecUpActivity) {
                showToast(CustKey.IN_AGAIN_MSG)
                LoginHelper.startLoginPage()
            }
            onUpdSkuData.observe(this@SpecUpActivity){
                showToast("操作成功")
                finish()
                hideKeyboard(binding.etName)
            }
            onSkuDetailData.observe(this@SpecUpActivity){
                //商品规格
                if(it.data.list.isNotEmpty()){
                    for (i in it.data.list.indices)
                        mList.add(CustSkuItemBean(images="",skuname=it.data.list[i].skuname,price=it.data.list[i].price.toString(),
                            skuprice=it.data.list[i].skuprice.toString(),stock=it.data.list[i].stock.toString()))

                    mAdapter.replaceData(mList)
                }
            }

        }
    }



    inner class ListAdapter : BaseQuickAdapter<CustSkuItemBean, BaseViewHolder>(R.layout.spec_item) {
        override fun convert(holder: BaseViewHolder, item: CustSkuItemBean) {
            holder.setText(R.id.etName,item.skuname)
                .setText(R.id.etPrice,item.price)
                .setText(R.id.etIntegral,item.skuprice)
                .setText(R.id.etStock,item.stock)


            if(TextUtils.isEmpty(item.skuname) || TextUtils.isEmpty(item.price)
                || TextUtils.isEmpty(item.skuprice)|| TextUtils.isEmpty(item.stock)){
                holder.getView<RoundLinearLayout>(R.id.llItem).delegate.strokeWidth=1
            }else{
                holder.getView<RoundLinearLayout>(R.id.llItem).delegate.strokeWidth=0
            }

            holder.getView<EditText>(R.id.etName).addTextChangedListener(object :
                TextWatcher {
                override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
                }
                override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
                }
                override fun afterTextChanged(p0: Editable?) {
                    loge("list监听 规格名称="+p0.toString())
                    mAdapter.data[holder.layoutPosition].skuname=p0.toString()
                }
            })
            holder.getView<EditText>(R.id.etPrice).addTextChangedListener(object :
                TextWatcher {
                override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
                }
                override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
                }
                override fun afterTextChanged(p0: Editable?) {
                    loge("list监听 零售价格="+p0.toString())
                    mAdapter.data[holder.layoutPosition].price=p0.toString()
                }
            })
            holder.getView<EditText>(R.id.etIntegral).addTextChangedListener(object :
                TextWatcher {
                override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
                }
                override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
                }
                override fun afterTextChanged(p0: Editable?) {
                    loge("list监听 积分数量="+p0.toString())
                    mAdapter.data[holder.layoutPosition].skuprice=p0.toString()
                }
            })
            holder.getView<EditText>(R.id.etStock).addTextChangedListener(object :
                TextWatcher {
                override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
                }
                override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
                }
                override fun afterTextChanged(p0: Editable?) {
                    loge("list监听 库存数量="+p0.toString())
                    mAdapter.data[holder.layoutPosition].stock=p0.toString()
                }
            })

        }
    }

}